<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-dtl', title: '退货明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">基础信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <customFormItem label="退库类型" name="transferType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.baseMatrType}"
                          :disabled="cpHasDtl"
                          help-tip="有明细后不可修改<br>不同出库类型可选退货明细不一样"
                          @change="transferTypeChange"
                          ref="transferType"
          />


          <customFormItem
            label="退库仓库" name="fromWarehouseName" :parent="_self" :form="form"
            help-tip="有明细后不可修改<br>筛选调拨到该仓库的数据"
            :type="constCommon.formItemType.slot.name"
            @focusTo="$refs.fromWarehouseName.focus()"
          >
            <template #content>
              <warehouseSelect
                :flagCenter="false"
                :idNe="form.toWarehouseId"
                v-model="form.fromWarehouseId"
                :valueDisplay="form.fromWarehouseName"
                @change="fromWarehouseChange"
                :disabled="propReadonly || cpHasDtl"
                ref="fromWarehouseName"
              />
            </template>
          </customFormItem>

          <customFormItem
            label="目标仓库" name="toWarehouseName" :parent="_self" :form="form"
            :disabled="cpHasDtl"
            help-tip="有明细后不可修改<br>筛选调拨从该仓库调拨的数据"
            :type="constCommon.formItemType.slot.name"
            @focusTo="$refs.toWarehouseName.focus()"
          >
            <template #content>
              <warehouseSelect
                :flagCenter="true"
                :idNe="form.fromWarehouseId"
                v-model="form.toWarehouseId"
                :valueDisplay="form.toWarehouseName"
                @change="toWarehouseChange"
                :disabled="propReadonly || cpHasDtl"
                ref="toWarehouseName"
              />
            </template>
          </customFormItem>


          <customFormItem
            label="消耗方式" name="settlementType" :parent="_self" :form="form"
            :type="constCommon.formItemType.selectStatic.name"
            :config="{ options:utils.getDictDataList(constCommon.dictType.settlementType) }"
            @change="settlementTypeChange"
            :disabled="cpSettlementTypeDisabled"
            help-tip="有明细后不可修改<br>用后结算从库存里面选择<br>出库结算从调拨明细里面选择"
          />

          <customFormItem
            label="退库日期" name="busDate" :parent="_self" :form="form"
            disabled
          />

          <customFormItem
            label="单号" name="busKey" :parent="_self" :form="form"
            disabled
            :config="{defaultValue: '系统自动生成'}"
          />


          <customFormItem
            label="经手人" name="busUser" :parent="_self" :form="form"
            disabled
          />


          <customFormItem
            label="备注" name="remark" :parent="_self" :form="form"
          />
        </template>
      </customForm>

      <div id="box-dtl" class="box-title">退货明细</div>
      <customTooltip title="扫描唯一码进行拣货或者取消拣货" v-show="!propReadonly && !propParent.cpFormNew" >
        <template #content>
          <FortenScan
            ref="scanInputDtl"
            propPlaceholder="扫描唯一码进行拣货或者取消拣货"
            @after-scan="barCodeScan"
            propType="uniqueCode"
            style="width: 450px;margin-top: 10px;display: inline-block; margin-right: 5px"/>

          <customButton :title="cpIsUsed ? '选择库存明细' : '选择调拨明细'" theme="primary" class="btn-scan"
                        @click="selectDtl"
          />
        </template>
      </customTooltip>
      <data-view
        propViewKey="wm_transfer_item_dept_return"
        :propInitData="form"
        :propParentData="propParent.viewFormData"
        ref="childDataView"
        :propsDisableDbClick="true"
        :propNoEditRow="true"
        :propParentPage="_self"
        :propAutoFetchData="false"
        @extra-button-click="extraButtonClick"
        :propHideFlowSelect="true"
        @afterTableDataChange="afterTableDataChange"
        :propFlowKey="propParent.propFlowKey"
        :propFilterBtn="propFilterBtn"
        :propTableHide="propParent.cpFormNew"
        propTableHideMsg="请先保存主单据再操作"
        @edit-input="rowEditInput"
      />
    </div>

     <!--出库消耗 settlementType: out 非标签管理 明细选择-->
     <tableDrawer
      ref="tableDrawerDtlOut"
      refName="tableDrawerDtlOut"
      viewKey="wm_stock_barcode"
      :queryWrapper="cpOutQueries"
      loadForce
      title="可退库存"
      subtitle="筛选所属物理仓库"
      :widthPer="80"
      :heightPx="-1"
      :widthPx="-1"
    />

    <!--扫码消耗 settlementType: used 标签管理 明细选择-->
    <tableDrawer
      ref="tableDrawerDtlUsed"
      refName="tableDrawerDtlUsed"
      viewKey="wm_transfer_red"
      :queryWrapper="cpUsedQueries"
      loadForce
      title="调拨明细"
      subtitle="筛选所属物理仓库"
      :widthPer="80"
      :heightPx="-1"
      :widthPx="-1"
    />

  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
import warehouseSelect from '@/components/custom/bus/select/warehouseSelect.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      txtScan: '',
    }
  },
  computed: {
    // 是否为标签管理
    cpIsUsed() {
      return this.form.settlementType == this.constCommon.dictType.settlementTypeUsed
    },
    // 是否有明细
    cpHasDtl() {
      return this.form.countDtl > 0
    },
    // 出库消耗
    cpOutQueries() {
      let wrapper = this.$newWrapper()
      wrapper.eq('warehouseId', this.form.fromWarehouseId)
        .eq('flagUniqueCode', 1)
        .eq('lockQty', 0)
      if (this.strings.isNotBlank(this.form.transferType)) {
        wrapper.eq('matrBaseType', this.form.transferType)
      }
      wrapper.ne('flagStockReagent', 1)
      return wrapper
    },
    // 扫码消耗
    cpUsedQueries() {
      let wrapper = this.$newWrapper()
      wrapper.eq('warehouseId', this.form.fromWarehouseId)
        .eq('flagUniqueCode', 1)
        .eq('lockQty', 0)
      wrapper.eq('baseType', this.form.transferType)
      wrapper.ge('packageQty', 0)
      wrapper.eq('flowStatus', 'end')
      return wrapper
    },
    // 消耗类型是否禁用
    cpSettlementTypeDisabled() {
      return this.cpHasDtl || this.utils.isBaseTypeLom(this.form.transferType)
    },
  },
  methods: {
    loadDtl() {
      if (!this.$refs.childDataView) {
        return
      }
      let $newWrapper = this.$newWrapper()
      if (!this.propParent.cpFormNew) {
        $newWrapper.eq('transferId', this.form.id)
      } else {
        $newWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper($newWrapper)
    },
    //扫码SN或RFID
    barCodeScan(txtScan) {
      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/transfer_item/scan',
        { autoUnlock: true, 'transferId': this.form.id, 'uniqueCode': txtScan, 'fromWarehouseId': this.form.fromWarehouseId }
      ).then(
        resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.loadDtl()
            this.afterTableDataChange()
            this.$set(this.$data, 'txtScan', null)
          }
          this.utilVue.loadHide()
        }
      )
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    },

    // 添加明细
    _saveBatchItem(stockList) {
      this.utilVue.loadShow(true)
      stockList.forEach(row => {
        row.transferId = this.form.id
        row.stockId = row.id
        if (!this.cpIsUsed) {
          row.itemIdReturnFrom = row.id
        }
        row.id = null
      })
      this.$ajax.post('/wm/transfer_item/addBySelect', stockList).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.loadDtl()
          this.afterTableDataChange()
        }
      })
    },

    // 添加明细
    saveBatchItem(stockList) {
      //主单据未保存
      if(this.propParent.cpFormNew) {
        this.propParent.ocAsynSaveViewForm(() => {
          this._saveBatchItem(stockList)
        })
        return
      }
      this._saveBatchItem(stockList)
    },

    // 扩展按钮事件
    extraButtonClick({ button, data, index }) {
      let buttonKey = button.key
    },

    //新增初始化
    toWarehouseInit() {
      if (!this.form.toWarehouseId) {
        return
      }
      let toWarehouse = this.propDictionaries.fromWarehouseId.filter(wh => wh.id == this.form.toWarehouseId)
      if (toWarehouse && toWarehouse.length > 0) {
        if (toWarehouse[0].flagCenter) { //如果是中心仓库的，只能是用后结算
          this.$set(this.form, 'settlementType', this.constCommon.dictType.settlementTypeUsed)
        }
      }
    },

    addNewInit() {
      this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)

      let getCurrentWarehouse = this.utils.getCurrentWarehouse()

      if (getCurrentWarehouse.flagCenter) {
        this.$set(this.form, 'toWarehouseId', getCurrentWarehouse.applyWarehouseId)
        this.$set(this.form, 'toWarehouseName', getCurrentWarehouse.applyWarehouseName)
      } else{
        this.$set(this.form, 'fromWarehouseId', getCurrentWarehouse.warehouseId)
        this.$set(this.form, 'fromWarehouseName', getCurrentWarehouse.warehouseName)
      }

      this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDateTimePattern))
      //分类
      // this.$set(this.form, 'transferType', this.constCommon.dictType.baseMatrTypeMatr)
      this.$set(this.form, 'flowStatus', 'start')
      // this.$set(this.form, 'settlementType', this.constCommon.dictType.settlementTypeUsed)
      this.$set(this.form, 'type', this.constCommon.dictType.wmInOrderTypeInDeptReturn)

      this.toWarehouseInit()
      this.$nextTick(() => {
        this.$refs.transferType.focus()
      })
    },

     // 选择结算类型
    settlementTypeChange(value) {
      this.$set(this.form, 'settlementType', value)
    },

    // 退库仓库 选择
    fromWarehouseChange(row) {
      this.$set(this.form, 'fromWarehouseName', row.name)
      this.$set(this.form, 'fromWarehouseId', row.id)
    },

     // 目标仓库 选择
     toWarehouseChange(row) {
      this.$set(this.form, 'toWarehouseName', row.name)
      this.$set(this.form, 'toWarehouseId', row.id)
    },

    // 过滤显示按钮
    propFilterBtn(btnList) {
      // 采购入库时，不要明细的添加按钮
      if (this.propReadonly) {
        return btnList.filter(btn => ['vb-search','vb-reset', 'vb-toggle'].includes(btn.code))
      }
      return btnList
    },

    selectDtl() {
      if (this.cpIsUsed) {
        this.$refs.tableDrawerDtlOut.show(this.saveBatchItem, true)
      } else {
        this.$refs.tableDrawerDtlUsed.show(this.saveBatchItem, true)
      }
    },
    rowEditInput({row, column}) {
      if (column.property == 'skuQty') {
        this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
        this.$set(row, 'packageQty', row.skuQty)
      }
    },
    //退库类型 修改后
    transferTypeChange() {
      if (this.utils.isBaseTypeLom(this.form.transferType)) {
        this.$set(this.form, 'settlementType', this.constCommon.dictType.settlementTypeOut)
      }
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        if (this.form.fromWarehouseId == this.form.toWarehouseId) {
          this.utilMessage.error('退库仓库和目标仓库不能是同一个')
          return false
        }
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        console.log(' this.form', this.form)
        // 设置元素默认值
        if (!this.form.id) {
          this.addNewInit()
        }
        this.loadDtl()
      },
      afterSave: () => {  },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        if (flowButtonKey == 'submit') {
          if (this.form.countDtl == 0) {
            this.utilMessage.error('退货明细为空，不能提交')
            return false
          }
        }

        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'printTransfer') { //打印明细
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'deptReturn', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        } else if (buttonKey == 'printTransferSum') { //打印汇总
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'deptReturnSum', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      },
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propFlowKey: String,
    propParam: Object
  },
  components: {
    customAnchor, warehouseSelect
  },
}
</script>
